package com.jackiechan.day18;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Test2_Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10000);
        Socket socket = ss.accept();
        Thread sendThread = new Send(socket);
        Thread receThread = new Rece(socket);
        sendThread.start();
        receThread.start();
        while (true) ;
    }
}

class Rece extends Thread {
    Socket socket = null;
    OutputStream tofile = new BufferedOutputStream(
            new FileOutputStream("E:\\scoket\\1.txt"));
    public Rece(Socket socket) throws FileNotFoundException {
        this.socket = socket;
    }
    @Override
    public void run() {
        try (InputStream in = socket.getInputStream())
        {
            System.out.println("等待接收");
            while (true) {
                try {
                    System.out.print((char) in.read());
                    tofile.write(in.read());
                }catch (IOException e){
                    e.printStackTrace();
                    break;
                }
                while (in.available() != 0) {
                    System.out.print((char) in.read());
                    tofile.write(in.read());
                }
                System.out.println("\n*****接收完成*****");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("接收异常");
            run();
        }
    }
}

class Send extends Thread {
    Socket socket = null;
    InputStream fromfile = new BufferedInputStream(
            new FileInputStream("E\\1.jpg"));
    int i;
    public Send(Socket socket) throws FileNotFoundException {
        this.socket = socket;
    }
    @Override
    public void run() {
        while (true) {
            try (OutputStream out = socket.getOutputStream())
            {
                System.out.println("请输入发送信息: ");
//                String msg = new Scanner(System.in).next();
//                out.write(msg.getBytes());
                while ((i = fromfile.read())!=-1){
                    out.write(i);
                }
                System.out.println("*****已发送*****");
//                out.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("发送异常");
                run();
            }
        }
    }
}
